package org.example.controller;

import lombok.extern.slf4j.Slf4j;
import org.example.service.ExcelFilterDedupService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * Excel过滤去重控制器
 * 提供Excel文件过滤和去重的REST API接口
 */
@Slf4j
@RestController
@RequestMapping("/api/excel-filter-dedup")
public class ExcelFilterDedupController {

    @Autowired
    private ExcelFilterDedupService excelFilterDedupService;

    /**
     * 处理Excel文件：过滤还款状态为-1的订单，按订单号和期数去重，并导出
     * @param file Excel文件
     * @param response HTTP响应
     * @throws IOException IO异常
     */
    @PostMapping("/process")
    public void processExcel(@RequestParam("file") MultipartFile file, 
                           HttpServletResponse response) throws IOException {
        try {
            // 验证文件
            validateFile(file);
            
            // 处理Excel文件
            excelFilterDedupService.processExcel(file, response);
            
        } catch (Exception e) {
            log.error("处理Excel文件失败", e);
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().write("{\"error\": \"处理失败: " + e.getMessage() + "\"}");
        }
    }

    /**
     * 获取Excel文件处理统计信息（不实际处理文件）
     * @param file Excel文件
     * @return 统计信息
     */
    @PostMapping("/statistics")
    public ResponseEntity<Map<String, Object>> getStatistics(@RequestParam("file") MultipartFile file) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            // 验证文件
            validateFile(file);
            
            // 获取统计信息
            Map<String, Object> statistics = excelFilterDedupService.getProcessStatistics(file);
            
            result.put("success", true);
            result.put("message", "统计信息获取成功");
            result.put("statistics", statistics);
            
            return ResponseEntity.ok(result);
            
        } catch (Exception e) {
            log.error("获取统计信息失败", e);
            result.put("success", false);
            result.put("message", "获取统计信息失败: " + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }

    /**
     * 处理Excel文件并导出到指定目录
     * @param file Excel文件
     * @param outputDir 输出目录路径（可选，默认为C:\AAAAmessage\）
     * @return 处理结果
     */
    @PostMapping("/process-to-directory")
    public ResponseEntity<Map<String, Object>> processExcelToDirectory(
            @RequestParam("file") MultipartFile file,
            @RequestParam(value = "outputDir", defaultValue = "C:\\AAAAmessage\\") String outputDir) {
        
        Map<String, Object> result = new HashMap<>();
        
        try {
            // 验证文件
            validateFile(file);
            
            // 处理Excel文件并导出到指定目录
            String outputFilePath = excelFilterDedupService.processExcelToDirectory(file, outputDir);
            
            result.put("success", true);
            result.put("message", "文件处理完成并已导出到指定目录");
            result.put("outputFilePath", outputFilePath);
            result.put("outputDir", outputDir);
            
            return ResponseEntity.ok(result);
            
        } catch (Exception e) {
            log.error("处理Excel文件失败", e);
            result.put("success", false);
            result.put("message", "处理失败: " + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }

    /**
     * 健康检查接口
     * @return 健康状态
     */
    @GetMapping("/health")
    public ResponseEntity<Map<String, Object>> health() {
        Map<String, Object> result = new HashMap<>();
        result.put("success", true);
        result.put("message", "Excel过滤去重服务运行正常");
        result.put("timestamp", System.currentTimeMillis());
        result.put("service", "ExcelFilterDedupService");
        
        return ResponseEntity.ok(result);
    }

    /**
     * 获取服务说明
     * @return 服务说明
     */
    @GetMapping("/info")
    public ResponseEntity<Map<String, Object>> getServiceInfo() {
        Map<String, Object> result = new HashMap<>();
        
        result.put("service", "Excel过滤去重服务");
        result.put("version", "1.0.0");
        result.put("description", "提供Excel文件过滤和去重功能");
        
        Map<String, Object> features = new HashMap<>();
        features.put("filter", "删除还款状态为-1的订单");
        features.put("deduplication", "按订单号和期数去重");
        features.put("export", "保持原有字段顺序导出");
        result.put("features", features);
        
        Map<String, Object> endpoints = new HashMap<>();
        endpoints.put("POST /api/excel-filter-dedup/process", "处理Excel文件并导出");
        endpoints.put("POST /api/excel-filter-dedup/process-to-directory", "处理Excel文件并导出到指定目录");
        endpoints.put("POST /api/excel-filter-dedup/statistics", "获取处理统计信息");
        endpoints.put("GET /api/excel-filter-dedup/health", "健康检查");
        endpoints.put("GET /api/excel-filter-dedup/info", "服务信息");
        result.put("endpoints", endpoints);
        
        Map<String, Object> requirements = new HashMap<>();
        requirements.put("fileFormat", "Excel文件(.xlsx或.xls)");
        requirements.put("requiredFields", new String[]{"下单订单号", "期数", "还款状态"});
        requirements.put("filterCondition", "还款状态 = -1");
        requirements.put("dedupKeys", new String[]{"下单订单号", "期数"});
        result.put("requirements", requirements);
        
        return ResponseEntity.ok(result);
    }

    /**
     * 验证上传的文件
     * @param file 上传的文件
     */
    private void validateFile(MultipartFile file) {
        if (file == null || file.isEmpty()) {
            throw new IllegalArgumentException("文件不能为空");
        }
        
        String originalFilename = file.getOriginalFilename();
        if (originalFilename == null) {
            throw new IllegalArgumentException("文件名不能为空");
        }
        
        if (!originalFilename.endsWith(".xlsx") && !originalFilename.endsWith(".xls")) {
            throw new IllegalArgumentException("文件格式不正确，请上传Excel文件(.xlsx或.xls)");
        }
        
        // 检查文件大小（限制为100MB）
        long maxSize = 100 * 1024 * 1024; // 100MB
        if (file.getSize() > maxSize) {
            throw new IllegalArgumentException("文件大小不能超过100MB");
        }
    }
}
